import {
  Inject,
  Controller,
  Get,
  Query,
  Body,
  UseGuard,
  Put,
  Files,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/api.user.service';
import {
  UserDTO,
  UpdateUserDTO,
  UserIdentityDTO,
  AdminUpdateUserDTO,
} from '../dto/user';
import { PageDTO } from '../dto/page';
import { AuthGuard } from '../guard/auth.guard';
import { UploadMiddleware } from '@midwayjs/busboy';
import { UploadFileInfo } from '@midwayjs/busboy';

@Controller('/user')
//使用@Controller 装饰器定义了一个控制器，路由前缀为 /api/user。这意味着所有与用户相关的请求都将以这个路径开头。
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;
  /**
   * @name getAllUser 管理员获取所有用户信息
   * @description GET /api/user/getAllUser
   * @returns {object} user - 用户信息
   */
  @UseGuard(AuthGuard)
  @Get('/getAllUser')
  async getAllUser(@Query() allUserDto: PageDTO): Promise<object> {
    if (allUserDto.type == 2) {
      throw new Error('type参数错误');
    }
    return await this.userService.getAllUser(allUserDto);
  }
  /**
   * @name getUser 获取用户信息
   * @description GET /api/user/getUser?userId=xxx
   * @param {string} userId - 用户ID
   * @returns {object} user - 用户信息
   */
  @UseGuard(AuthGuard)
  @Get('/getUser')
  async getUser(@Query('userId') userId: UserDTO['userId']): Promise<object> {
    // 检查 uid 是否存在
    return await this.userService.findAccount('userId', userId);
  }
  /**
   * @name uploadImg 上传凭证图片
   * @description Put /user/uploadImg
   * @param {File} files - 上传的图片文件
   * @returns {string} - 上传状态
   */
  @Put('/uploadImg', { middleware: [UploadMiddleware] })
  async uploadImg(@Files('files') files: Array<UploadFileInfo>): Promise<any> {
    // 上传文件
    return await this.userService.uploadImg(files);
  }
  /**
   * @name updateUserInfo 更新用户信息
   * PUT /api/user/updateUserInfo
   * @param {UpdateUserDTO} updateUserDto - 用户信息
   * @returns {boolean}  - 更新成功
   */
  @Put('/updateUserInfo')
  async updateUserInfo(@Body() updateUserDto: UpdateUserDTO): Promise<boolean> {
    const filteredData = Object.entries(updateUserDto).reduce(
      (acc, [key, value]) => {
        if (value != null) {
          // 同时过滤掉 null 和 undefined
          acc[key] = value;
        }
        return acc;
      },
      {} as UpdateUserDTO
    );
    if (Object.keys(filteredData).length === 0) {
      throw new Error('更新数据为空');
    }
    const userId = this.ctx.state.user.userId;
    return await this.userService.updateUserInfo(userId, filteredData);
  }
  /**
   * @name   adminUpdateUserInfo 管理员修改用户信息
   * @description PUT /api/user/adminUpdateUserInfo
   * @param {UpdateUserDTO} updateUserDto - 用户信息
   * @returns {boolean}  - 更新成功
   */
  @UseGuard(AuthGuard)
  @Put('/adminUpdateUserInfo')
  async adminUpdateUserInfo(
    @Body() updateUserDto: AdminUpdateUserDTO
  ): Promise<boolean> {
    if (!updateUserDto.userId) {
      throw new Error('不能为空用户');
    }
    const userId = updateUserDto.userId;
    const user = await this.userService.userDao.findAccount('user_id', userId);
    if (!user) {
      throw new Error('用户不存在');
    }
    if (updateUserDto.remakePassword === true) {
      updateUserDto.password = '888888';
    }
    const filteredData = Object.entries(updateUserDto).reduce(
      (acc, [key, value]) => {
        if (value != null) {
          // 同时过滤掉 null 和 undefined
          acc[key] = value;
        }
        return acc;
      },
      {} as AdminUpdateUserDTO
    );
    if (Object.keys(filteredData).length === 1) {
      throw new Error('更新数据为空');
    }
    return await this.userService.updateUserInfo(userId, filteredData);
  }
  /**
   * @name getUserInfo 获取用户信息
   * @description post /api/user/getUserInfo
   * @returns {string} token - 用户凭证
   */
  @Get('/getUserInfo')
  async getUserInfo(): Promise<string> {
    return await this.userService.getUserInfo();
  }
  /**
   * @name getUserIdentityImg 管理员获取用户验证身份图片
   * @description get /api/user/getUserIdentityImg
   * @returns {object}  - 用户身份证图片
   */
  @UseGuard(AuthGuard)
  @Get('/getUserIdentityImg')
  async getUserIdentityImg(@Query() pageDto: PageDTO): Promise<object> {
    return await this.userService.getUserIdentityImg(pageDto);
  }
  /**
   * @name approveUserIdentityImg 管理员审批用户验证图片
   * @description put /api/user/approveUserIdentityImg
   * @param {string} userId - 用户ID
   * @returns {boolean}  - 更新成功
   */
  @UseGuard(AuthGuard)
  @Put('/approveUserIdentityImg')
  async approveUserIdentityImg(
    @Body() userIdentityDto: UserIdentityDTO
  ): Promise<boolean> {
    if (userIdentityDto.validFlag === 0) {
      if (!userIdentityDto.text) {
        throw new Error('驳回原因不能为空');
      }
    }
    const user = await this.userService.findAccount(
      'user_id',
      userIdentityDto.userId
    );
    if (!user) {
      throw new Error('用户不存在');
    }
    return await this.userService.approveUserIdentityImg(userIdentityDto);
  }
}
